package com.example.kotlinlearn.recycler

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlinlearn.R

class ListItemAdapter(val itemList:List<ListItem>):
    RecyclerView.Adapter<ListItemAdapter.ViewHolder>() {

    /**
     * 初始化控件
     */
        inner class ViewHolder(view :View) : RecyclerView.ViewHolder(view){
            val itemImage:ImageView = view.findViewById(R.id.listImage)
            val itemText:TextView = view.findViewById(R.id.listText)
        }


    /**
     *必须重写以下三个方法
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item,parent,false)
        val viewHolder = ViewHolder(view)
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            val item = itemList[position]
            Toast.makeText(parent.context,"点击${item.name}",Toast.LENGTH_SHORT).show()
        }
        viewHolder.itemImage.setOnClickListener {
            val position = viewHolder.adapterPosition
            Toast.makeText(parent.context,"点击了图片$position",Toast.LENGTH_SHORT).show()

        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
        super.onBindViewHolder(holder, position, payloads)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = itemList[position]
        holder.itemImage.setImageResource(item.ImageId)
        holder.itemText.text = item.name
    }

    override fun getItemCount()=itemList.size
}